#include "tcp_server.h"

int CTcpServer::Start(const char* pcIP,const int iPort)
{
#ifdef WIN32
	WSADATA wsaData;
	if ( WSAStartup(0x202,&wsaData) != 0) {
		WSACleanup();
		return SOCK_STARTUP_ERR;
	}
#endif

	_addrLocalAddr.sin_family = AF_INET;
    _addrLocalAddr.sin_addr.s_addr = inet_addr(pcIP); 
    _addrLocalAddr.sin_port = htons(iPort);

	//socket(): TCP socket
    _iLocalSocket = socket(AF_INET, SOCK_STREAM ,0);
    if (_iLocalSocket == INVALID_SOCKET)
	{
        return SOCK_SOCKET_ERR;
    }

	//bind()
	if (bind(_iLocalSocket,(struct sockaddr*)&_addrLocalAddr,sizeof(_addrLocalAddr) ) 
		== SOCKET_ERROR) 
	{
		return SOCK_BIND_ERR;
	}

	//listen
	if (listen(_iLocalSocket,SOMAXCONN) == SOCKET_ERROR) {
		return SOCK_LISTEN_ERR;
	}

	//
	int iFromLen;
	struct sockaddr_in addrFromAddr;
	int iSocket;
	while(1)
	{
		iFromLen =sizeof(addrFromAddr);
		//
		// accept() doesn't make sense on UDP, since we do not listen()
		//

		iSocket = accept(_iLocalSocket,(struct sockaddr*)&addrFromAddr, &iFromLen);
		if (iSocket == INVALID_SOCKET) {
			WSACleanup();
			return SOCK_ACCEPT_ERR;
		}

		boost::thread sockThead(&CTcpServer::AcceptThread, iSocket);

		_thdsThreads.add_thread(&sockThead);
	}

	return SOCK_OK;


}

int CTcpServer::Stop()
{
	return 0;
}
